package com.service;

import com.domain.BlogArticle;
import com.domain.BlogComment;
import com.domain.Comment;
import com.domain.Statistic;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mapper.CommentMapper;
import com.mapper.StatisticMapper;
import com.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CommentService {
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    StatisticMapper statisticMapper;
    @Autowired
    private CommentRepository commentRepository;
    @Cacheable(cacheNames = "comment",unless = "#result==null")
    public Comment findById(int comment_id){
        Optional<Comment> optional = commentRepository.findById(comment_id);

        if (optional.isPresent()){
            return optional.get();
        }
        return null;
    }
    @CachePut(cacheNames = "comment",key = "#result.id")
    public Comment updateComment(Comment comment){
        commentRepository.updateComment(comment.getAuthor(), comment.getAId());
        return comment;
    }
    @CacheEvict(cacheNames = "comment")
    public void deleteComment(int comment_id){ commentRepository.deleteById(comment_id);}
    public void pushComment(BlogComment comment){
        commentMapper.pushComment(comment);
        Statistic statistic = statisticMapper.selectStatisticWithArticleId(comment.getArticleId());
        statistic.setCommentsNum(statistic.getCommentsNum()+1);
        statisticMapper.updateArticleHitsWithId(statistic);
    }
    public PageInfo<BlogComment> getComments(Integer aid,int page, int count){
        PageHelper.startPage(page,count);
        List<BlogComment> commentList = commentMapper.selectCommentWithPage(aid);
        PageInfo<BlogComment> commentInfo = new PageInfo<>(commentList);
        return commentInfo;
    }
}
